package com.ruicar.afs.cloud.image.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.image.condition.AuditCondition;
import com.ruicar.afs.cloud.image.config.FileProperties;
import com.ruicar.afs.cloud.image.config.GwtFastdfsProperties;
import com.ruicar.afs.cloud.image.service.ComAttaManageService;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.store.enums.FileServiceEnum;
import com.ruicar.afs.cloud.image.store.enums.IsViewEnum;
import com.ruicar.afs.cloud.image.store.feign.BaoDingPlaceApiFeign;
import com.ruicar.afs.cloud.image.store.feign.ImageStoreApiFeign;
import com.ruicar.afs.cloud.image.store.feign.TianJinPlaceApiFeign;
import com.ruicar.afs.cloud.image.util.ImageUtil;
import com.ruicar.afs.cloud.image.vo.AuditFileStatusVo;
import com.ruicar.afs.cloud.image.vo.DownFileVo;
import com.ruicar.afs.cloud.image.vo.DownVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author infinity
 * @version 1.0
 * @date 2020/7/13 14:34
 */
@RestController
@Slf4j
@RequestMapping("/audit")
@AllArgsConstructor
@Api(value = "audit", description = "影像审核")
public class AuditFileController {
    private final ComAttachmentFileService comAttachmentFileService;
    private final ImageStoreApiFeign imageStoreApiFeign;
    private final BaoDingPlaceApiFeign baoDingPlaceApiFeign;
    private  final TianJinPlaceApiFeign tianJinPlaceApiFeign;
    private final GwtFastdfsProperties fastdfsProperties;
    private FileProperties fileProperties;
    private ImageUtil imageUtil;
    private final ComAttaManageService comAttaManageService;

    @PostMapping(value = "/getAllFileList")
    @ApiOperation(value = "初始化数据")
    public IResponse getAllFileList(@RequestBody @Validated AuditCondition auditCondition) {
        return IResponse.success(comAttachmentFileService.getAllFileList(auditCondition));
    }

    @PostMapping(value = "/getLoanAllFileList")
    @ApiOperation(value = "初始化数据")
    public IResponse getLoanAllFileList(@RequestBody @Validated AuditCondition auditCondition) {
        return IResponse.success(comAttaManageService.getLoanAllFileList(auditCondition));
    }
    @PostMapping(value = "/getHistoryVersion")
    @ApiOperation(value = "初始化数据")
    public IResponse getHistoryVersion(@RequestParam("busiNo") String busiNo,@RequestParam("busiNode") String busiNode) {
        return IResponse.success(comAttachmentFileService.getHistoryVersion(busiNo,busiNode,""));
    }

    @PostMapping(value = "/zipDownloadFile")
    @ApiOperation(value = "批量下载附件")
    public void zipDownloadFile(HttpServletResponse response, @RequestBody DownVo downVo) {
        String zipName = "";
        // 临时文件
        String fileName = File.separator + DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumber() + File.separator;
        String destPath = fileProperties.getTempDir() + File.separator + DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumber() + File.separator;
        // 2. 从远端接口获取数据
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", comAttachmentFileService.getAuthorization());
        Assert.isTrue(downVo.getData().size() > 0, "未选择附件！");
        for (DownFileVo vo : downVo.getData()) {
            byte[] fileByte = imageStoreApiFeign.downFile(vo.getMd5Value(), fastdfsProperties.getSceneId(), vo.getFilename(), IsViewEnum.download.getCode(), null, headers);
            if (fileByte.length > 0) {
                FileUtil.writeBytes(fileByte, destPath + File.separator + fileName + vo.getFilename());
            }
        }
        BufferedInputStream bufferedInputStream = null;
        try {
            File zipFile = ZipUtil.zip(destPath + File.separator + fileName);
            response.reset(); // 重点突出
            if (FileUtil.exist(destPath)) {
                File file = FileUtil.file(zipFile);
                bufferedInputStream = FileUtil.getInputStream(file);
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;filename=" + HttpUtil.encodeUtf8("附件下载.zip"));
                IoUtil.copy(bufferedInputStream, response.getOutputStream(), 1024);
                response.getOutputStream().flush();
                IoUtil.close(bufferedInputStream);
                //删除打包zip文件
                FileUtil.del(destPath);
                zipName = zipFile.getName();
                return;
            }
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (Exception e) {
            IoUtil.close(bufferedInputStream);
            FileUtil.del(destPath);
            log.error("文件下载失败:" + e.getMessage());
        } finally {
            IoUtil.close(bufferedInputStream);
        }
    }

    @PostMapping(value = "/rotateSave")
    @ApiOperation(value = "旋转保存")
    public IResponse rotateSave() {
        return IResponse.success(true);
    }

    @PostMapping(value = "/updateFileStatus")
    @ApiOperation(value = "修改附件文件状态")
    public IResponse updateFileStatus(@RequestBody @Validated AuditFileStatusVo vo) {
        return IResponse.success(comAttachmentFileService.updateFileStatus(vo));
    }

    @PostMapping(value = "/getDealerSign/{applyNo}")
    @ApiOperation(value = "查看经销商预留印鉴")
    public IResponse getDealerSign(@RequestBody @Validated String applyNo) {
        return IResponse.success(comAttachmentFileService.getDealerSign(applyNo));
    }

    @GetMapping(value = "/getFile/{username}/{fileService}/{fileType}/{isThumb}/{md5}")
    @ApiOperation(value = "预览图片")
    public void getFile(HttpServletResponse response,
                        @PathVariable("username") String username,
                        @PathVariable("fileService") String fileService,
                        @PathVariable("fileType") String fileType,
                        @PathVariable("isThumb") String isThumb,
                        @PathVariable("md5") String md5 ) throws Exception {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", comAttachmentFileService.getAuthorization());
        byte[] fileByte=new byte[0];
        if(fileService.equals(FileServiceEnum.BaoDingPlace.getCode())){
            fileByte = baoDingPlaceApiFeign.downFile(md5, fastdfsProperties.getSceneId(), "", IsViewEnum.download.getCode(), isThumb, headers);
        }else if(fileService.equals(FileServiceEnum.TianJinPlace.getCode())){
            fileByte = tianJinPlaceApiFeign.downFile(md5, fastdfsProperties.getSceneId(), "", IsViewEnum.download.getCode(), isThumb, headers);
        }else{
            fileByte = imageStoreApiFeign.downFile(md5, fastdfsProperties.getSceneId(), "", IsViewEnum.download.getCode(), isThumb, headers);
        }

        if (fileType.equals("pdf")) {
            response.setContentType(MediaType.APPLICATION_PDF_VALUE);
        } else if (fileType.equals("mp4")) {
            response.setContentType("video/mp4");
        } else {
            if(StringUtils.isNotBlank(username)){
                fileByte=imageUtil.setWatermark(fileByte,username,fileType);
            }
            response.setContentType(MediaType.ALL_VALUE);
        }
        response.getOutputStream().write(fileByte);
        response.getOutputStream().flush();
    }
    @PostMapping(value = "/getFileByUniqueCode")
    @ApiOperation(value = "根据唯一标识获取文件")
    public IResponse getFileByUniqueCode(@RequestParam("uniqueCodes") String uniqueCodes
                                        ,@RequestParam("busiNo") String busiNo
                                        ,@RequestParam("belongNo") String belongNo) {
        return IResponse.success(comAttaManageService.getFileByUniqueCode(uniqueCodes,busiNo,belongNo));
    }

    @PostMapping(value = "/setFileStandard")
    @ApiOperation(value = "修改文件状态为合格")
    public IResponse setFileStandard(@RequestParam("contractNo") String contractNo,
                            @RequestParam("attachmentCode") String attachmentCode) {
        comAttaManageService.setFileStandard(contractNo,attachmentCode);
        return IResponse.success("修改成功！");
    }

}
